package info.niwota.gae;

import info.niwota.org.json.JSONObject;

import java.io.IOException;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class BaseServlet extends HttpServlet {
	protected static final String HOTWEB_PROXY_BASE = "http://hotwebproxy.appspot.com";

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		try {
			if (handle(req, resp)) {
				return;
			}

			handleNotFound(req, resp);
		} catch (Exception e) {
			e.printStackTrace();
			handleError(req, resp, e);
		}
	}

	protected boolean handle(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		return false;
	}

	protected void handleError(HttpServletRequest req,
			HttpServletResponse resp, Throwable e) throws IOException {
		final String msg = e.getMessage();
		resp.setContentType("text/plain");
		resp.getWriter().println(msg);
	}
	
	protected void sendLogin(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		UserService userService = UserServiceFactory.getUserService();
		StringBuffer sb = req.getRequestURL();
		final String url = sb.append(query(req)).toString();
		
		if (userService.isUserLoggedIn()) {
			resp.sendRedirect(url);
			return;
		}
		
		resp.setHeader("X-Return-Url", url);
        resp.sendRedirect("http://hotwebproxy.appspot.com/login");
	}
	

	protected void sendLogout(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		UserService userService = UserServiceFactory.getUserService();
		//go to local home if not logged in
		if (!userService.isUserLoggedIn()) {
			resp.sendRedirect("/");
			return;
		}
		URL ctxUrl = new URL(req.getRequestURL().toString());
		URL url =  new URL(ctxUrl, "/");
		
		resp.setHeader("X-Return-Url", url.toString());
		resp.sendRedirect("http://hotwebproxy.appspot.com/logout");
	}
	
	protected void handleNotFound(HttpServletRequest req,
			HttpServletResponse resp) throws IOException {
		final String uri = req.getRequestURI();
		resp.setContentType("text/plain");
		resp.getWriter().println("Not found: " + uri);
	}

	protected void handleJSON(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String uri = HOTWEB_PROXY_BASE + req.getRequestURI() + "?"
				+ req.getQueryString();
		resp.sendRedirect(uri);
	}

	protected void sendError(HttpServletRequest req, HttpServletResponse resp,
			String message) throws IOException {
		resp.setContentType("text/plain");
		resp.getWriter().println("ERR: " + message);

	}

	protected void sendJSON(HttpServletRequest req, HttpServletResponse resp, JSONObject data)
			throws IOException {
		resp.setContentType("application/json");
		resp.getWriter().println(data.toString());
	}

	protected void sendOk(HttpServletRequest req, HttpServletResponse resp,
			String message) throws IOException {
		resp.setContentType("text/plain");
		resp.getWriter().println("OK: " + message);
	}

	protected int parseInt(String s, int defval) {
		try {
			return Integer.parseInt(s);
		} catch (Exception e) {

		}
		return defval;
	}

	protected long parseLong(String s, long defval) {
		try {
			return Long.parseLong(s);
		} catch (Exception e) {

		}
		return defval;
	}

	protected boolean isEmpty(String s) {
		return (s == null || s.equals(""));
	}
	
	protected String query(HttpServletRequest req) {
		String q = req.getQueryString();
		return (q == null ? "" : "?" + q);
	}
}
